package cn.cmvideo.springboot;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * Java 8 API 添加了一个新的抽象称为流Stream 可以以一种声明的方式处理数据<br>
 * 这种风格将要处理的元素集合看做一种流，流在管道中传输，并且可以在管道的节点上进行处理，比如筛选、排序、聚合等。
 * 元素在管道中经过中间操作（intermediate operation）的处理，最后有最终操作（terminal operation）得到前面的处理结果
 * <p>
 * +--------------------+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+
 * ------+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+------+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+-
 * --+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+-------+<br>
 * | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|<br>
 * +--------------------+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+
 * ------+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+------+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+-
 * --+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+-------+
 * </p>
 * 
 * @author Administrator
 *
 */
public class Java8Stream
{

	public static void main(String[] args)
	{
		List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
		List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
		List<Integer> integers = Arrays.asList(1, 2, 13, 4, 15, 6, 17, 8, 19);
		// 输出10个随机数
		Random random = new Random();

		System.out.println("使用 Java 8: ");
		System.out.println("列表: " + strings);

		long count = strings.stream().filter(string -> string.isEmpty()).count();
		System.out.println("空字符串数量为: " + count);

		count = strings.stream().filter(string -> string.length() == 3).count();
		System.out.println("字符串长度为 3 的数量为: " + count);

		List<String> collect = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
		System.out.println("排除数组中空字符串，筛选后的列表: " + collect);

		String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(","));
		System.out.println("排除数组中空字符串，合并字符串: " + mergedString);

		List<Integer> squaresList = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
		System.out.println("Squares List: " + squaresList);

		System.out.println("列表: " + integers);
		IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();
		System.out.println("列表中最大的数 : " + stats.getMax());
		System.out.println("列表中最小的数 : " + stats.getMin());
		System.out.println("所有数之和 : " + stats.getSum());
		System.out.println("平均数 : " + stats.getAverage());

		System.out.println("随机数: ");
		random.ints().limit(10).sorted().forEach(System.out::println);
		
		// 并行处理
		count = strings.parallelStream().filter(string -> string.isEmpty()).count();
		System.out.println("空字符串的数量为: " + count);
	}
}
